package cn.iocoder.yudao.module.resource;

import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.*;

import java.io.File;
import java.io.IOException;

public class MinimaxVoiceClone {

    private static final String GROUP_ID = "1891387532482974328";
    private static final String API_KEY = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJHcm91cE5hbWUiOiLmtbfonrrnlKjmiLdfMzQ4MjQ3NTIxNTk5OTM0NDY5IiwiVXNlck5hbWUiOiLmtbfonrrnlKjmiLdfMzQ4MjQ3NTIxNTk5OTM0NDY5IiwiQWNjb3VudCI6IiIsIlN1YmplY3RJRCI6IjE4OTEzODc1MzI0OTU1NTcxOTQiLCJQaG9uZSI6IjEzMTQ2NDUyNzMzIiwiR3JvdXBJRCI6IjE4OTEzODc1MzI0ODI5NzQzMjgiLCJQYWdlTmFtZSI6IiIsIk1haWwiOiIiLCJDcmVhdGVUaW1lIjoiMjAyNS0wMy0xOSAxODoxNTowNCIsIlRva2VuVHlwZSI6MSwiaXNzIjoibWluaW1heCJ9.RNpvN2ftuC0dACMpaGYbHp6-y81k_OWhnk54t3jtBSqo8rjfI9xI9Wq-o0hisH6jPXcr08kiSpFzWO0CVpo9Wu3P-cY0tKtttTbPFzUHCa3aBYojUKZZrQJZitOGS7X1ZMh54CsdCtH3XvVEqu-4CSio271crezaxsZ367QFMboMq1q7fL8cpA2OaP9XeQLWE8jX9HP8EZNw2K7VWRDj1arf2OAkM-JjytHf5DY4kiDm-QO6FYYfr592x-k4k-JqVynOourbTX58zKdHA4q8EjlYccU9MMLw_Qr8GYQ7tGjXD-N0JT2k1v9h_UQ1BIS1rmK5tVS34rZ11TroSeh-9w";
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final OkHttpClient httpClient = new OkHttpClient();

    public static void main(String[] args) {
        try {
            // 1. 上传复刻音频
            String fileId = uploadFile("E:\\dudu\\docs\\00声纹原音-第2版-10s-20s\\20号-百度导航-小七-甜度8-媚度4-尖度5.MP3", "voice_clone");
            System.out.println("File ID: " + fileId);

            // 2. 上传示例音频
            //String promptFileId = uploadFile("E:\\ai\\MaskGCT-fix\\demo\\02-南晚姐姐1号-小姐姐-柔媚-甜度5-媚度7-尖度7.MP3", "prompt_audio");
            //System.out.println("Prompt File ID: " + promptFileId);

            //String fileId = "258273080222099";
            //String promptFileId = "249140457455856";

            String voiceId = "minimax_" + IdUtil.objectId();
            // 3. 音频复刻请求
            String cloneResponse = voiceClone(
                    fileId,
                    voiceId,
                    "你好啊，我想你了"
            );
            System.out.println("Clone Response: " + cloneResponse);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String uploadFile(String filePath, String purpose) throws IOException {
        // 构建 multipart 请求体
        File file = new File(filePath);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("purpose", purpose)
                .addFormDataPart(
                        "file",
                        file.getName(),
                        RequestBody.create(file, MediaType.parse("application/octet-stream"))
                )
                .build();

        // 构建请求
        Request request = new Request.Builder()
                .url("https://api.minimax.chat/v1/files/upload?GroupId=" + GROUP_ID)
                .header("Authorization", "Bearer " + API_KEY)
                .post(requestBody)
                .build();

        // 发送请求并解析响应
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("上传失败: " + response);
            }
            JsonNode root = objectMapper.readTree(response.body().string());
            return root.get("file").get("file_id").asText();
        }
    }

    private static String voiceClone(
            String fileId,
            String voiceId,
            String text
    ) throws IOException {
        // 构建 JSON 请求体
        /*ObjectNode clonePrompt = objectMapper.createObjectNode()
                .put("prompt_audio", promptFileId)
                .put("prompt_text", promptText);*/

        ObjectNode payload = objectMapper.createObjectNode()
                .put("file_id", Long.parseLong(fileId))
                .put("voice_id", voiceId)
                //.put("text_validation", textValidation)
                //.put("accuracy", accuracy);
                //.set("clone_prompt", clonePrompt);
                .put("text", text)
                .put("model", "speech-02-hd")
                .put("need_noise_reduction", false);

        // 构建请求
        Request request = new Request.Builder()
                .url("https://api.minimax.chat/v1/voice_clone?GroupId=" + GROUP_ID)
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .post(RequestBody.create(payload.toString(), MediaType.parse("application/json")))
                .build();

        // 发送请求并返回响应
        try (Response response = httpClient.newCall(request).execute()) {
            String traceId = response.header("Trace-ID");
            System.out.println("Trace-ID: " + traceId);
            if (!response.isSuccessful()) {
                throw new IOException("克隆失败: " + response);
            }
            return response.body().string();
        }
    }
}
